package com.geeksaga.common.util;

import javax.servlet.http.HttpServletRequest;


import org.apache.commons.fileupload.ProgressListener;

import com.geeksaga.domain.UploadInfo;

/**
 * @author newbie
 * @since 0.1
 */
public class ProgressListnerImpl implements ProgressListener {
	private HttpServletRequest request;
	private long startTime;
	private long megaBytes = -1;
	private int fileCount = -1;

	public ProgressListnerImpl() {
	}

	public ProgressListnerImpl(HttpServletRequest request) {
		this.fileCount++;
		this.request = request;
		this.startTime = System.currentTimeMillis();
	}

	public void update(long pBytesRead, long pContentLength, int pItems) {
		long mBytes = pBytesRead / 1000000;
		if (megaBytes == mBytes) {
			return;
		}
		
		megaBytes = mBytes;

		long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;

		if (pContentLength == -1) {
		} else {
//			try {
//				Thread.sleep(30);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			
			request.getSession().setAttribute("uploadInfo",
					new UploadInfo(fileCount, pContentLength, pBytesRead, elapsedTime, "progress"));
		}
	}
}